﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Common.Utilities;


namespace DiscoveryLogic.Analytics.BusinessLogic.Entities
{
    public class DataSetManager
    {
        public static List<EntityDataSet> GetEntityDataSets(EntityType entityType)
        {
            List<EntityDataSet> entityDataSets = new List<EntityDataSet>();
            string appFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appFolderPath = Path.Combine(appFolderPath, "Network Data");
            if (!Directory.Exists(appFolderPath))
                Directory.CreateDirectory(appFolderPath);
            DirectoryInfo dirInfo = new DirectoryInfo(appFolderPath);
            string extension = EntityTypeUtil.GetEntityDataSetFileExtension(entityType);
            
            FileInfo[] files = dirInfo.GetFiles("*"+extension, SearchOption.TopDirectoryOnly);
            if (files != null && files.Length > 0)
            {
                foreach (FileInfo file in files)
                {
                    if (!file.Name.ToLower().EndsWith(extension))
                        continue;
                    string dataSetName = Path.GetFileNameWithoutExtension(file.FullName);
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(file.FullName);
                    EntityDataSet dataSet = EntityDataSet.Read(xDoc);
                    entityDataSets.Add(dataSet);
                }
            }

            return entityDataSets;
        }

        public static List<EntityBase> ReadEntitySetData(
            EntityType entityType, string setName)
        {
            string appFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appFolderPath = Path.Combine(appFolderPath, "Network Data");
            if (!Directory.Exists(appFolderPath))
                Directory.CreateDirectory(appFolderPath);
            string extension = EntityTypeUtil.GetEntityDataSetFileExtension(entityType);
            string filePath = Path.Combine(appFolderPath, setName + extension);
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(filePath);
            EntityDataSet entityDataSet = EntityDataSet.Read(xDoc);
            return entityDataSet.Entities;
        }

        public static void Delete(EntityDataSet entityDataSet)
        {
            string fileExtension = DataFolder.EntityDataSetFileExtension(entityDataSet.EntityType);
            string dataSetFilePath =
                Path.Combine(DataFolder.NetworkDataFolder, entityDataSet.DataSetName + fileExtension);
            if(File.Exists(dataSetFilePath))
                File.Delete(dataSetFilePath);
        }
    }
}
